# Function to prepare Data and run stan to sample from posteror 
######################

est_stan_sim <- function(dat,iteration=200, chains=1, 
                     model="model_graded_response.stan",
                     ...){
  
  # Install required Packages
  require(reshape2)
  require(rstan)  
  rstan_options(auto_write = TRUE) # Multipel Cores
  options(mc.cores = parallel::detectCores())
  
  # Prepare Data
  cd   <- melt(dat, id.vars = c("expert","issue"))
  cd   <- na.omit(cd)
  
  # Stan Data
  uc <- function(x) length(unique(as.factor(x)))
  standata <- list(T = uc(cd$value), J = uc(cd$variable), K = uc(cd$issue),N = nrow(cd), 
                   I = uc(cd$expert),
                   jj = as.numeric(as.factor(cd$variable)),
                   kk = as.numeric(cd$issue),
                   ii = as.numeric(as.factor(cd$expert)),
                   y = cd$value )
  
  # Initial Value Function; lstoetze: nu is fixed otherwise nummerical errors
  init_fun <- function(T = uc(cd$value), J = uc(cd$variable), K = uc(cd$issue),I = uc(cd$expert)) {
    list(
      tau = sort(runif(T-1,-2,2))
      ,bk_free  = runif(K,1,1) 
      ,nu_free = runif(J,1,1)
    )
  }
  
  # Call stan
  fit <- stan(file = model, data = standata, init = init_fun,
              iter = iteration, chains = chains
              , ...)
  
  # Return Fit
  return(fit)
}

